//
//  LOAudioStreamer.m
//  LOAudioStreamer
//
//  Created by 何欣 on 15/6/3.
//  Copyright (c) 2015年 何欣. All rights reserved.
//

#import "LOAudioStreamer.h"
#import <AVFoundation/AVFoundation.h>

@interface LOAudioStreamer ()
{
    BOOL _isPlaying;//标记是否正在播放
    BOOL _isPrepared;//标记播放器是否准备完成
}
@property(nonatomic,retain)AVPlayer *audioPlayer;//音乐播放器

@property(nonatomic,retain)NSTimer *timer;

@end

@implementation LOAudioStreamer

+(instancetype)sharedStreamer{
    
    static LOAudioStreamer *streamer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        streamer = [[LOAudioStreamer alloc]init];
    });
    return streamer;
}

-(instancetype)init{

    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(handleEndTimeNotification) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

-(void)handleEndTimeNotification{
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioStreamerDidFinishPlaying:)]) {
        [self.delegate audioStreamerDidFinishPlaying:self];
    }
}

#pragma mark-  重写audioStreamer GET 方法  lazyLoading
-(AVPlayer *)audioPlayer{
    if (!_audioPlayer) {
        self.audioPlayer = [[AVPlayer alloc]init];
    }
    return _audioPlayer;
}


-(void)setAudioMetadataWithURL:(NSString *)urlString{
    //根据指定的url创建AVPlayerItem 对象
//    AVPlayerItem *currentItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:urlString]];
    
    AVPlayerItem *currentItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:urlString]];
    [currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    //根据给定item对象替换音频播放器当前的item
    [self.audioPlayer replaceCurrentItemWithPlayerItem:currentItem];
}



- (void)setLocalMetadataWithURL:(NSString *)urlString
{
    NSURL *url = [NSURL fileURLWithPath:urlString];
    AVAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil];

    AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
    
    
    
    self.audioPlayer = [[AVPlayer alloc] initWithPlayerItem:anItem];
   
}

#pragma mark- Audio Control-

-(void)play{
    _isPlaying = YES;
    [self.audioPlayer play];
    if (self.timer) {
        return;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(handleTimerAction:) userInfo:nil repeats:YES];
}

-(void)pause{
    _isPlaying = NO;
    [self.audioPlayer pause];
    [self.timer invalidate];
    _timer = nil;

}

-(void)stop{
    [self.audioPlayer pause];
    //设置播放器跳转h回0秒 完成播放器停止功能
    [self.audioPlayer seekToTime:CMTimeMake(0, self.audioPlayer.currentTime.timescale)];
}

-(void)setVolume:(float)volume{
    self.audioPlayer.volume = volume;
    
}

-(float)volume{
    return  self.audioPlayer.volume;
}

-(float)druation{
    NSLog(@"%f",CMTimeGetSeconds([self.audioPlayer.currentItem.asset duration]));
    
    if (CMTIME_IS_INVALID([self.audioPlayer.currentItem.asset duration])) {
       return 0;
    }
  //  totalDuration = CMTimeGetSeconds(self.audioPlayer.currentItem.asset duration);
    
    
    return CMTimeGetSeconds([self.audioPlayer.currentItem.asset duration]);
}

- (float)progress{
    NSLog(@"%f",CMTimeGetSeconds(self.audioPlayer.currentItem.currentTime))
    if (CMTIME_IS_INVALID([self.audioPlayer.currentItem currentTime])) {
        return 0;
    }

    return CMTimeGetSeconds([self.audioPlayer.currentItem currentTime]);
}


- (float)totalBuffer
{
    NSArray *array = self.audioPlayer.currentItem.loadedTimeRanges;
    
    // 本次缓冲的时间范围
    
    if (CMTIME_IS_INVALID([array.firstObject CMTimeRangeValue].duration)) {
        return 0;
    }
    
    CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];;
    
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    
    // 缓冲总长度
    NSTimeInterval totalBuffer = startSeconds + durationSeconds;
    
    NSLog(@"共缓冲：%.2f", totalBuffer);
    return totalBuffer;
}


- (void)seekToTime:(float)time{
    [self pause];

    [self.audioPlayer seekToTime:CMTimeMake(time, 1) completionHandler:^(BOOL finished) {
        [self play];
    }];
}


-(void)handleTimerAction:(NSTimer *)sender{
    if (self.delegate && [self.delegate respondsToSelector:@selector(audioStreamer:didPlayingWithProgress:)]) {
        float progress = CMTimeGetSeconds(self.audioPlayer.currentTime);
        [self.delegate audioStreamer:self didPlayingWithProgress:progress];
    }
    
}

-(BOOL)isPlaying{
    return _isPlaying;
}

-(BOOL)isPrepared{

    return _isPrepared;
}

-(BOOL)isPlayingCurrentAudioWithURL:(NSString *)urlString{
    NSString *currentUrlStr = [(AVURLAsset *)self.audioPlayer.currentItem.asset URL].absoluteString;
    return [currentUrlStr isEqualToString:urlString];    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    NSLog(@"%@",change);
    
    switch ([[change objectForKey:@"new"]integerValue]) {
        case AVPlayerItemStatusUnknown:
            break;
        case AVPlayerItemStatusReadyToPlay:
            _isPrepared = YES;
            break;
        case AVPlayerItemStatusFailed:
            break;
        default:
            break;
    }
}

@end
